package com.itheima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.itheima.common.pojo.TbOrder;
import com.itheima.common.pojo.TbUser;
import com.itheima.common.response.OrderVo;
import com.itheima.common.response.UserOrderVo;
import com.itheima.user.feign.OrderFeign;
import com.itheima.user.mapper.UserMapper;
import com.itheima.user.service.UserService;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

/**
 * @作者 itcast
 * @创建日期 2020/10/17 14:33
 **/
@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    OrderFeign orderFeign;

    @Override
    public UserOrderVo findUserById(String username) {
        // 1. 根据username查询出 user信息
        TbUser tbUser = userMapper.selectOne(Wrappers.<TbUser>lambdaQuery().eq(TbUser::getUsername, username));
        // 2. 远程查询所有订单信息  Feign
        List<TbOrder> list = orderFeign.findList(username);
        // 3. 将查询到的user  和 订单信息 封装成一个VO对象
        // UserOrderVo vo= view object  数据更安全  5kb 1kb
        UserOrderVo userOrderVo = parseUserOrderVo(tbUser, list);
        return userOrderVo;
    }
    private UserOrderVo parseUserOrderVo(TbUser tbUser,List<TbOrder> list){
        UserOrderVo vo = new UserOrderVo();
        // 将 tbUser里面的对应属性 拷贝到 vo的对应属性上
        try {
            BeanUtils.copyProperties(vo,tbUser);
            List<OrderVo> orderVoList = new ArrayList<>();
            for (TbOrder tbOrder : list) {
                OrderVo orderVo = new OrderVo();
                BeanUtils.copyProperties(orderVo,tbOrder);
                orderVoList.add(orderVo);
            }
            vo.setTbOrders(orderVoList);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return vo;
    }



}
